<?php
namespace Home\Controller;
use Think\Controller;

class PublicController extends Controller
{
	// 登陆
	public function login()
	{
		if(IS_AJAX){
			$inputData = I('post.');
			$model = D('user');
			$result = $model -> where("username = '$inputData[username]' and userpass = " . "'" . md5($inputData['userpass']) . "'") -> find();
			if($result) {
				session('home.username', $result['username']);
				session('home.islogin','1');
				$this -> ajaxReturn(array('url' => '/home/index/index', 'status' => '0'));
			}else{
				$this -> ajaxReturn(array('msg' => '用户名或密码错误！'));
			}
		}else{
			$this -> display();
		}
	}
	// 注册
	public function register()
	{
		if(IS_AJAX){
			$inputData = I('post.');
			$model = D('user');
			// 验证
			if(!$model -> create($inputData)) {
				$this -> ajaxReturn(array('msg' => $model -> getError()));
			}else{
				// 查重
				$preventRepeat = $model -> where("username = '$inputData[username]' and branch = '$inputData[branch]'") -> find();
				if($preventRepeat){
					$this -> ajaxReturn(array('msg' => '用户名和部门重复！'));
				}else{
					$insertData = $model -> add(
						array(
							'username' => $inputData['username'],
							'userpass' => md5($inputData['password']),
							'branch' => $inputData['branch']
						)
					);
					if($insertData) {
						$this -> ajaxReturn(array('msg' => '注册成功，请登陆！', 'url' => '/home/public/login', 'status' => 1));
					}else{
						$this -> ajaxReturn(array('msg' => '服务器异常,注册失败！'));
					}
				}
			}
		}else{
			$this -> display();
		}
	}
	// 登出
	public function loginout()
	{
		session(null);
		$url = U('home/public/login');
		echo "<script>window.location.href='$url'</script>";
	}
}